package org.sws.trigger.job;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.sws.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import org.sws.domain.strategy.service.IRaffleAward;
import org.sws.domain.strategy.service.IRaffleStock;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author sws
 * @Date 2025/3/10 10:18
 * @description: 更新奖品库存任务，异步更新数据库，降低io压力
 */
@Slf4j
@Component
public class UpdateAwardStockJob {
    @Resource
    private IRaffleStock raffleStock;
    @Resource
    private IRaffleAward raffleAward;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private ThreadPoolExecutor executor;
    @Scheduled(cron = "0/5 * * * * ?")
    public void exec(){
        RLock lock = redissonClient.getLock("big-market-UpdateAwardStockJob");
        try {
            boolean isLocked = lock.tryLock(3, 0, TimeUnit.SECONDS);
            if (!isLocked) {return;}
            // 查询奖品配置
            List<StrategyAwardStockKeyVO> strategyAwardStockKeyVOS = raffleAward.queryOpenActivityStrategyAwardList();
            if(strategyAwardStockKeyVOS.isEmpty()){
                return;
            }
            for (StrategyAwardStockKeyVO strategyAwardStockKeyVO : strategyAwardStockKeyVOS) {
                executor.execute(() -> {
                    try {
                        StrategyAwardStockKeyVO queueStrategyAwardStockKeyVO = raffleStock.takeQueueValue(strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId());
                        if (null == queueStrategyAwardStockKeyVO) {
                            return;
                        }
                        raffleStock.updateStrategyAwardStock(queueStrategyAwardStockKeyVO.getStrategyId(), queueStrategyAwardStockKeyVO.getAwardId());
                        log.info("定时任务，更新奖品消耗库存 成功 strategyId:{} aRwardId:{}", queueStrategyAwardStockKeyVO.getStrategyId(), queueStrategyAwardStockKeyVO.getAwardId());
                    } catch (Exception e) {
                        log.error("定时任务，更新奖品消耗库存失败 strategyId:{} awardId:{}", strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId());
                    }
                });
            }
        } catch( Exception e) {
            log.error("定时任务，更新奖品消耗库存 失败", e);
        }finally{
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
